import {combineReducers} from 'redux';
import {ADD_TODO, HIDE_LOADING, SET_VISIBILITY_FILTER, SHOW_LOADING, TOGGLE_TODO, VisibilityFilters} from '../actions';

const {SHOW_ALL} = VisibilityFilters;

function visibilityFilter (state = SHOW_ALL, action) {
  switch (action.type) {
    case SET_VISIBILITY_FILTER:
      return action.filter;
    default:
      return state;
  }
}

let nextTodoId = 0;

function todos (state = [], action) {
  switch (action.type) {
    case ADD_TODO:
      return [
        ...state,
        {
          id: nextTodoId++,
          text: action.text,
          completed: false
        }
      ];
    case TOGGLE_TODO:
      return state.map((todo, index) => {
        if (index === action.index) {
          return Object.assign({}, todo, {
            completed: !todo.completed
          })
        }
        return todo;
      });
    default:
      return state;
  }
}

function spin (state = {spinning: false}, action) {
  switch (action.type) {
    case SHOW_LOADING:
      return {
        spinning: true,
      };
    case HIDE_LOADING:
      return {
        spinning: false
      };
    default:
      return state;
  }
}

const reducers = combineReducers({
  spin,
  visibilityFilter,
  todos,
});

/**
 * combineReducers的写法等价于
 function todoApp (state = {}, action) {
  return {
    visibilityFilter: visibilityFilter(state.visibilityFilter, action),
    todos: todos(state.todos, action)
  };
}
 */

export default reducers;
